import cookie from 'vue-cookies'
import router from '@/router'
import { ElMessage } from 'element-plus'

/**
 * 获取uuid
 */
export function getUUID () {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16)
  })
}
/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth (key) {
  const authorities = JSON.parse(sessionStorage.getItem('b2cAuthorities') || '[]')
  if (authorities.length) {
    for (const i in authorities) {
      const element = authorities[i]
      if (element === key) {
        return true
      }
    }
  }
  return false
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate (data, id = 'id', pid = 'parentId') {
  const res = []
  const temp = {}
  for (const datum of data) {
    temp[datum[id]] = datum
  }
  for (const datum of data) {
    if (temp[datum[pid]] && datum[id] !== datum[pid]) {
      if (!temp[datum[pid]].children) {
        temp[datum[pid]].children = []
      }
      if (!temp[datum[pid]]._level) {
        temp[datum[pid]]._level = 1
      }
      datum._level = temp[datum[pid]]._level + 1
      temp[datum[pid]].children.push(datum)
    } else {
      res.push(datum)
    }
  }
  return res
}

/**
 * 将数组中的parentId列表取出，倒序排列
 * @param {*} data
 * @param {*} id
 * @param {*} val
 */
export function idList (data, val, id = 'id') {
  const res = []
  idListFromTree(data, val, res, id)
  return res
}

/**
 * @param {*} data
 * @param {*} id
 * @param {*} val
 * @param {*} res
 * @param {*} children
 */
function idListFromTree (data, val, res = [], id = 'id', children = 'children') {
  for (const element of data) {
    if (element[children]) {
      if (idListFromTree(element[children], val, res, id, children)) {
        res.push(element[id])
        return true
      }
    }
    if (element[id] === val) {
      res.push(element[id])
      return true
    }
  }
}

/**
 * 清除登录信息
 */
export function clearLoginInfo () {
  cookie.remove('b2cAuthorization')
  router.options.isAddDynamicMenuRoutes = false
}

/**
 * 判断富文本是否为全空格
 * @param {String} str
 * @returns
 */
export function isHtmlNull (str) {
  if (!str) {
    return true
  }
  const html = str
    .replace(/<(?!img).*?>/g, '')
    .replace(/&nbsp;/gi, '')
    .replace(/(\n)/g, '')
  if (html === '') return true
  const regu = '^[ ]+$'
  const re = new RegExp(regu)
  return re.test(html)
}

/**
 * 判断富文本有无超出字数限制
 * @param {String} str
 * @return {Boolean} true/false
 */
export function validHtmlLength (str) {
  if (!str) {
    return false
  }
  if (str.replace(/<[^<>]+>/g, '').length > 65535) {
    ElMessage.error(
      `${$t('tip.currentWordCount') + str.replace(/<[^<>]+>/g, '').length},${$t(
        'weixin.wordsLimit'
      )}${65535}`
    )
    return true
  } else {
    return false
  }
}

// 计算每个sku后面有多少项
export function getLevels (tree) {
  const level = []
  for (let i = tree.length - 1; i >= 0; i--) {
    if (tree[i + 1] && tree[i + 1].tagItems) {
      level[i] = tree[i + 1].tagItems.length * level[i + 1] || 1
    } else {
      level[i] = 1
    }
  }
  return level
}

/**
 * 笛卡尔积运算
 * @param  {[type]} tree   [description]
 * @param  {Array}  stocks [description]
 * @param defaultObj
 * @return {{}}        [description]
 */
export function flatten (tree, stocks = [], defaultObj) {
  // 返回结果
  const result = []
  // sku的数据
  let skuLen = 0
  // 记录已存在的stock的数据
  const stockMap = {}
  // sku等级关系
  const level = getLevels(tree)
  // 没有参数时
  if (tree.length === 0) {
    if (stocks && stocks.length === 1 && (!stocks[0].properties || stocks[0].properties === '')) {
      return stocks
    } else {
      return [Object.assign({}, defaultObj)]
    }
  }
  // 计算sku数据
  tree.forEach(sku => {
    const { tagItems } = sku
    if (!tagItems || tagItems.length === 0) return true
    skuLen = (skuLen || 1) * tagItems.length
  })
  // 根据已有的stocks生成一个map
  stocks.forEach(stock => {
    const { properties, ...attr } = stock
    stockMap[properties] = attr
  })
  // 生成笛卡尔积
  for (let i = 0; i < skuLen; i++) {
    const mapKey = []
    const mapKeyEn = []
    const temp = {}
    tree.forEach((sku, column) => {
      const { tagItems } = sku
      let item = {}
      if (!tagItems || tagItems.length === 0) return true
      if (tagItems.length > 1) {
        // 计算当前sku的行数
        const row = Number.parseInt(i / level[column], 10) % tagItems.length
        item = tree[column].tagItems[row]
      } else {
        item = tree[column].tagItems[0]
      }
      if (item.pic) {
        temp.pic = item.pic
      }
      if (!sku.tagName || !item.propValue) return
      mapKey.push(`${sku.tagName}:${item.propValue}`)
      mapKeyEn.push(`${sku.tagNameEn || sku.tagName}:${item.propValueEn || item.propValue}`)
    })
    const { ...data } = stockMap[mapKey.join(';')] || {}
    temp.properties = mapKey.join(';')
    temp.propertiesEn = mapKeyEn.join(';')
    // 从map中找出存在的sku并保留其值
    result.push({ ...defaultObj, ...data, ...temp })
  }
  return result
}

/**
* 文件地址校验
* @param fileUrl 获取到的文件路径
*/
export function checkFileUrl (fileUrl) {
  const baseUrl = import.meta.env.VITE_APP_RESOURCES_URL
  const rex = new RegExp(baseUrl)
  if (fileUrl && !rex.test(fileUrl.trim())) {
    return baseUrl + fileUrl
  } else {
    return fileUrl
  }
}
